from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
import pdb
import django
import os, time

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
django.setup()
import logging
from user.dataCheck import DataCheck
from software.views.view_download import download
from software.models import SoftwareVersion
from user.models import User
from announcement.models import Announcement
from notice.models import NoticeInfo
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")

datacheck = DataCheck()


def getSoftNotice(request, *args, **kwargs):
    """
        url: '/announcement/softwareGet/',
        method: 'post',
        inputData: {
            token: data.token,//用户密钥
            page: data.page,
            maxItem: data.maxItem,
        },
        resData: {
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum': null,//检索到总消息
            'noticeList': [{
                'id': null,//通知id,
                'userName': null,//用户名称
                'softwareName': null,//软件名称
                'operate': null,//管理人员:  1软件审核通过 2软件审核未通过 3软件发布 4软件下线
                                //使用人员： 1软件审核通过（本地仓库） 2软件发布
                                //开发人员： 1软件审核通过 2软件审核未通过 3软件上传

            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = datacheck.getUser(requestParam['token'])
    noticeList = []
    filterDict = {
        # 'user': user,
        'announcementType': 1,
        'announcementUserType__icontains': str(user.userType)
    }
    # pdb.set_trace()
    announcement = Announcement.objects.filter(**filterDict).order_by('-createTime')
    if announcement.exists():
        totalNum = len(announcement)
        for announcementItem in announcement:
            anno = Announcement.objects.filter(isRead=user,id=announcementItem.id)
            if anno.exists():
                annoIsRead = '1'
            else:
                annoIsRead = '0'            
            item = {
                'id': announcementItem.id,
                # 'userName': announcementItem.softwareVersion.software.user.name,
                'userName': announcementItem.user.username,
                'softwareName': announcementItem.softwareVersion.softwareName,
                'versionName': announcementItem.softwareVersion.version,
                'operate': announcementItem.content,
                'softwareId': announcementItem.softwareVersion.software.id,
                'softwareVersion': announcementItem.softwareVersion.id,
                'isRead':annoIsRead
            }
            noticeList.append(item)
        result = noticeList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                     requestParam[
                                                                                                         'page'] *
                                                                                                     requestParam[
                                                                                                         'maxItem'])]
    else:
        totalNum = 0
        result = []
    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "noticeList": result
    }
    logger_request.info(data)
    return JsonResponse(data)


def getRunLog(request, *args, **kwargs):
    """
        url: '/announcement/qtDemandGet/',
        method: 'post',
        inputData: {
            token: data.token,//用户密钥
            page: data.page,
            maxItem: data.maxItem,
            noticeType: data.noticeType,//0需求 1问题
        },
        resData: {
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum': null,//检索到总消息
            'noticeList': [{
                'id': null,//noticeId,
                'userName': null,//用户名称
                'softwareName': null,//软件名称
                'operate': null,//管理人员:  1提问 2回答
                                //使用人员（只能看到有浏览权限的软件相关问题需求）： 1提出 2回答
                                //开发人员（只能看到管理人员允许开发人员处理的）： 1提出 2回答

            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = datacheck.getUser(requestParam['token'])
    noticeList = []
    filterDict = {
        'announcementUserType__icontains': str(user.userType)
    }
    if requestParam['noticeType'] == '0':
        filterDict['announcementType'] = 2
    elif requestParam['noticeType'] == '1':
        filterDict['announcementType'] = 3
    else:
        pass
    # pdb.set_trace()
    if requestParam['noticeType'] == '0':
        announcement = Announcement.objects.filter(**filterDict).order_by('-createTime')
        if announcement.exists():
            totalNum = len(announcement)
            for announcementItem in announcement:
                anno = Announcement.objects.filter(isRead=user,id=announcementItem.id)
                if anno.exists():
                    annoIsRead = '1'
                else:
                    annoIsRead = '0' 
                item = {
                    'id': announcementItem.id,
                    'userName': announcementItem.user.name,
                    'softwareName': announcementItem.softwareVersion.softwareName,
                    'versionName': announcementItem.softwareVersion.version,
                    'operate': announcementItem.content,
                    'isRead':annoIsRead
                }
                noticeList.append(item)
            result = noticeList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                         requestParam[
                                                                                                             'page'] *
                                                                                                         requestParam[
                                                                                                             'maxItem'])]
        else:
            totalNum = 0
            result = []
    elif requestParam['noticeType'] == '1':
        announcement = Announcement.objects.filter(**filterDict).order_by('-createTime')
        if announcement.exists():
            totalNum = len(announcement)
            for announcementItem in announcement:
                anno = Announcement.objects.filter(isRead=user,id=announcementItem.id)
                if anno.exists():
                    annoIsRead = '1'
                else:
                    annoIsRead = '0' 
                item = {
                    'id': announcementItem.id,
                    'userName': announcementItem.user.name,
                    'softwareName': announcementItem.softwareVersion.softwareName,
                    'versionName': announcementItem.softwareVersion.version,
                    'operate': announcementItem.content,
                    'isRead':annoIsRead
                }
                noticeList.append(item)
            result = noticeList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                         requestParam[
                                                                                                             'page'] *
                                                                                                         requestParam[
                                                                                                             'maxItem'])]
        else:
            totalNum = 0
            result = []
    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "noticeList": result
    }
    logger_request.info(data)
    return JsonResponse(data)


def createAnnouncement(userId, type, num, userType, softwareVersionId):
    """
    :param type:  question need software
    :param userType:  admin, develop, user
    :param id:  id
            num operate
    :return:
    """
    # if userType == '1':
    #     announcementUserType = 1
    # elif userType == '2':
    #     announcementUserType = 2
    # elif userType == '3':
    #     announcementUserType = 3
    # else:
    #     announcementUserType = 2
    if type == 'question':
        ANNOUNCEMENTTYPE = 3
    elif type == 'need':
        ANNOUNCEMENTTYPE = 2
    elif type == 'software':
        ANNOUNCEMENTTYPE = 1
    else:
        ANNOUNCEMENTTYPE = 4
    softwareVersion = SoftwareVersion.objects.filter(pk=softwareVersionId)
    # user = User.objects.filter(pk=userId)
    if softwareVersion.exists():
        softwareVersionItem = softwareVersion[0]
        # userItem = user[0]
        Announcement.objects.create(
            user_id=userId,
            announcementUserType=userType,
            content=num,
            softwareVersion=softwareVersionItem,
            announcementType=ANNOUNCEMENTTYPE
        )
    else:
        pass
        print(1)


def announcementCreate(type, num, userType, softwareVersionId, userId, IdNum):
    """
    :param type:  question need software
    :param userType:  admin, develop, user
    :param id:  id
            num operate
    :return:
    """
    # if userType == '1':
    #     announcementUserType = 1
    # elif userType == '2':
    #     announcementUserType = 2
    # elif userType == '3':
    #     announcementUserType = 3
    # else:
    #     announcementUserType = 2
    if type == 'question':
        ANNOUNCEMENTTYPE = 3
    elif type == 'need':
        ANNOUNCEMENTTYPE = 2
    elif type == 'software':
        ANNOUNCEMENTTYPE = 1
    else:
        ANNOUNCEMENTTYPE = 4
    softwareVersion = SoftwareVersion.objects.filter(pk=softwareVersionId)
    user = User.objects.filter(pk=userId)
    if softwareVersion.exists():
        softwareVersionItem = softwareVersion[0]
        userItem = user[0]
        Announcement.objects.create(
            user=userItem,
            announcementUserType=userType,
            content=num,
            softwareVersion=softwareVersionItem,
            announcementType=ANNOUNCEMENTTYPE,
            IdNum=IdNum,
        )
    else:
        pass
        print(1)



def getRead(request, *args, **kwargs):
    """
        url    : /announcement/read/
        method : POST

    :param request:
            token:data.token,//用户密钥
            id:data.id,
            noticeType:data.noticeType,//0需求 1问题 2软件

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam['token'])

    # pdb.set_trace()
    if requestParam['noticeType'] == '0' or  requestParam['noticeType'] == '1' or requestParam['noticeType'] == '2':
        anno = Announcement.objects.filter(isRead=user,pk=requestParam['id'])
        if anno.exists():
            pass
        else:
            annoment = Announcement.objects.get(pk=requestParam['id'])
            annoment.isRead.add(user)
    elif requestParam['noticeType'] == '3':
        notice = NoticeInfo.objects.filter(isRead=user,pk=requestParam['id'])
        if notice.exists():
            pass
        else:
            noticeItem = NoticeInfo.objects.get(pk=requestParam['id'])
            noticeItem.isRead.add(user)
    
    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


if __name__ == '__main__':
    for i in range(5):
        createAnnouncement(type='need', num=1, userType='123', softwareVersionId=29)
